package com.ybkj.o2o.zhuanche.manager.impl;

import com.ybkj.o2o.zhuanche.common.DataGrid;
import com.ybkj.o2o.zhuanche.entity.OrderOrbit;
import com.ybkj.o2o.zhuanche.manager.OrderOrbitManager;
import com.ybkj.o2o.zhuanche.service.OrderOrbitService;

import org.apache.ibatis.session.RowBounds;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DefaultOrderOrbitManager implements OrderOrbitManager {
  @Autowired
  private OrderOrbitService orderOrbitService;
  /**
   * 查询订单轨迹点.
   */
  
  public DataGrid<OrderOrbit> findAll(int page, int rows) {
    int offset = (page - 1) * rows;

    RowBounds rowBounds = new RowBounds(offset, rows);

    List<OrderOrbit> content = orderOrbitService.findAll(rowBounds);
    long total = orderOrbitService.count();

    DataGrid<OrderOrbit> dataGrid = new DataGrid<>();
    dataGrid.setRows(content);
    dataGrid.setTotal(total);

    return dataGrid;
  }

  @Override
  public OrderOrbit findByOrderId(Long orderId) {

    return orderOrbitService.findByOrderId(orderId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insert(Long orderId, String xml) {

    Document doc = null;

    try {

      doc = DocumentHelper.parseText(xml);

    } catch (DocumentException ex) {
      ex.printStackTrace();
    }

    if (null != doc) {
      Element root = doc.getRootElement();

      Element element = root.element("order");

      // 解析xml节点
      OrderOrbit orderOrbit = new OrderOrbit();
      orderOrbit.setOrderId(orderId);
      orderOrbit.setXml(element.element("locations").asXML());
      orderOrbitService.insert(orderOrbit);
    }
  }


}
